//Третья лаба по jdbc
package dao;

import dao.bean.User;
import dao.dao.JdbcUtils;
import dao.exception.NotUniqueUserEmailException;
import dao.exception.NotUniqueUserLoginException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class UserDaoBatchInsert {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    private Connection getConnection() throws SQLException {
        // error: empty url - no driver
        // error: wrong db name
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/production_eshop", "root", "2479");
    }
public void insert(User [] users) throws SQLException,
        NotUniqueUserLoginException, NotUniqueUserEmailException {
    
Connection conn = getConnection();        
        java.sql.PreparedStatement ps = null;
        try {
            conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            conn.setAutoCommit(false);            
            
//            if (existWithLogin0(conn, user.getLogin())) {
//                throw new NotUniqueUserLoginException("Login '" + user.getLogin() + "' doubled");
//            }
//            if (existWithEmail0(conn, user.getEmail())) {
//                throw new NotUniqueUserEmailException("Email '" + user.getEmail() + "' doubled");
//            }
            for (int i = 0; i < users.length; i++){
               
            ps = conn.prepareStatement("INSERT INTO User (login, email) VALUES (?, ?)");
            ps.setString(1, users[i].getLogin());
            ps.setString(2, users[i].getEmail());
            ps.addBatch();           
            }
            
            int [] updateCounts = ps.executeBatch();
            conn.commit();
        
        } catch (SQLException e) {
            JdbcUtils.rollbackQuietly(conn);
            throw e;
        } finally {
            //JdbcUtils.closeQuietly(stmt);
            JdbcUtils.closeQuietly(conn);
        }
    }

    public static void main(String[] args) throws SQLException, NotUniqueUserLoginException, NotUniqueUserEmailException {
        User [] users = new User[1];
        users[0] = new User(0);
        users[0].setLogin("Alya");
        users[0].setEmail("alya@i.ua");
        UserDaoBatchInsert uIns = new UserDaoBatchInsert();
        uIns.insert(users);
    }

}
